package cn.aop;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.Arrays;

@Component("loggerAspect")
@Aspect
public class LoggerAspect {
    private static final Logger log= LoggerFactory.getLogger(LoggerAspect.class);

    @Pointcut(value = "execution(* cn.printer..*.*(..))")
    public void pt(){}

    @Before(value = "pt()")
    public void before(JoinPoint jp){
        int random=(int)(Math.random()*10);
        log.info("LoggerAspect前置增强，正在调用{}的{}方法，参数为{}：",jp.getTarget(),jp.getSignature().getName(), Arrays.toString(jp.getArgs()));
        if(random<5){
            log.info("检查正常");
        }
        else {
            throw new RuntimeException("检查异常");
        }
    }

    @AfterReturning(value = "pt()",returning = "result")
    public void afterReturning(JoinPoint jp,Object result){
        log.info("LoggerAspect后置增强，正在调用{}的{}方法，为{},",jp.getTarget(),jp.getSignature().getName(),result);
    }

    @AfterThrowing(value = "pt()",throwing = "e")
    public void afterThrowing(JoinPoint jp,Throwable e){
        log.info("LoggerAspect异常抛出增强模拟业务异常回滚事务，异常信息为："+e.getMessage());
        log.info("session.rollback()");
    }

    @After(value = "pt()")
    public void after(){
        log.info("MyBatisUtils.closeSqlSession(sqlSession);");
    }
}
